'use strict'

process.chdir(__dirname)

const fs = require('fs')
const fsp = fs.promises

let fname = process.argv[2]

if (!fname) {
  console.error('less filename')
  process.exit(1)
}

let cur_dir = __dirname

let data = fs.readFileSync('./ldd_cmd_so', {encoding: 'utf8'})

let datalines = data.split('\n').filter(p => p.length > 0)

let libtable = {}
let name, ind, endi, file

for (let dl of datalines) {
  ind = dl.indexOf('=>')

  if (ind < 0 && !(/\/lib64\/ld\-linux.*\.so.*/i).test(dl)) continue

  endi = dl.indexOf('(0x')

  if (ind < 0) {
    name = dl.substring(0, endi).trim().split('/')
    name = name[name.length-1]
  } else {
    name = dl.substring(0, ind).trim()
    /**
     * 不同Linux发行版一个很操蛋的问题是，对不同的库依赖路径存在差异。
     * */
    let orgname = name
    if (name.indexOf('/') >= 0) {
      name = name.split('/').filter(p => p.length > 0)
      name = name[name.length - 1]
      libtable[`FUCK:${name}`] = orgname
    }

  }

  if (ind < 0) {
    file = dl.substring(0, endi).trim()
  } else {
    file = dl.substring(ind+2, endi).trim()
  }

  if (!libtable[name]) libtable[name] = file
}

//console.log(libtable)
//process.exit(0)

function parsePath(file) {
  let arr = file.split('/')
  return arr.slice(0, arr.length-1).join('/') + '/'
}

let fdir = ''
let kn

for (let k in libtable) {
  kn = k
  if (k.indexOf('FUCK:') === 0) {
    kn = k.substring(5)
  }

  try {
    fdir = parsePath(libtable[k])
    let local_fdir = './nroot' + fdir
    try {
      fs.accessSync(local_fdir)
    } catch (err) {
      fs.mkdirSync(local_fdir, {recursive: true})
    }

    let fst = fs.lstatSync(libtable[k])

    if (fst.isSymbolicLink()) {
      let linkFile = fs.readlinkSync(libtable[k], {encoding: 'utf8'}) 
      let destFile = ''

      let ind = linkFile.indexOf('/')
      if (ind === 0) {
        destFile = './nroot' + linkFile
        let subpath = parsePath(destFile)
        try {
          fs.accessSync(subpath)
        } catch (err) {
          console.log('mkdir ===> ', subpath)
          fs.mkdirSync(subpath, {recursive: true})
        }
      } else {
        destFile = local_fdir + linkFile
      }

      console.log('====>', libtable[k], destFile, kn)

      fs.copyFileSync(libtable[k], destFile);
      
      if (ind === 0) {
        try {
          fs.accessSync('./nroot' + libtable[k])
          fs.unlinkSync('./nroot' + libtable[k])
        } catch (err) {
          console.error(err)
        }
        fs.symlinkSync(linkFile, './nroot' + libtable[k])
      } else {

        process.chdir(local_fdir);

        try {
          fs.accessSync(kn)
          fs.unlinkSync(kn)
        } catch (err) {

        }

        fs.symlinkSync(linkFile, kn);

        process.chdir(cur_dir)
      }
      
    } else {
      //console.log('--not link', k)
      /**
       * 不同的Linux发行版对/lib64 的处理是不同的，有的是软链接、有的是目录。
       * */
      console.log('copy:', libtable[k], ' ====> ', local_fdir + kn)
      fs.copyFileSync(libtable[k], local_fdir + kn)
    }

  } catch (err) {
    console.error(err)
  }
}

